'use strict';

exports.main = async (event, context) => {
	const { status, page = 1, pageSize = 10, userId } = event;
	
	if (!userId) {
		return {
			code: -1,
			message: '用户未登录'
		}
	}
	
	const db = uniCloud.database();
	const tripCollection = db.collection('trips');
	const courseCollection = db.collection('courses');
	
	try {
		// 构建查询条件
		const where = { userId };
		if (status !== undefined) {
			where.status = status;
		}
		
		// 获取行程总数
		const countRes = await tripCollection.where(where).count();
		const total = countRes.total;
		
		// 获取行程列表
		const tripRes = await tripCollection
			.where(where)
			.orderBy('createTime', 'desc')
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.get();
		
		// 获取课程详情
		const courseIds = tripRes.data.map(trip => trip.courseId);
		const courseRes = await courseCollection
			.where({
				_id: db.command.in(courseIds)
			})
			.get();
		
		// 合并行程和课程信息
		const trips = tripRes.data.map(trip => {
			const course = courseRes.data.find(c => c._id === trip.courseId);
			return {
				...trip,
				course
			};
		});
		
		return {
			code: 0,
			message: '获取成功',
			data: {
				list: trips,
				total,
				page,
				pageSize
			}
		}
	} catch (error) {
		return {
			code: -1,
			message: '获取失败'
		}
	}
}; 